package club.jdiy.admin.service.impl;

import club.jdiy.admin.dao.DictDao;
import club.jdiy.admin.dao.DictItemDao;
import club.jdiy.admin.entity.Dict;
import club.jdiy.admin.entity.DictItem;
import club.jdiy.admin.service.DictItemService;
import club.jdiy.core.base.JDiyBaseService;
import club.jdiy.core.ex.JDiyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class DictItemServiceImpl extends JDiyBaseService<DictItem, DictItemDao, Long>
        implements DictItemService {
    @Override
    @Transactional
    public DictItem logicSave(DictItem vo) {
        Dict dict = dictDao.findById(vo.getDict().getId()).orElseThrow(() -> new JDiyException("获取字典信息失败．"));

        if (vo.getVal() == null) vo.setVal(vo.getTxt());
        if (!Boolean.TRUE.equals(dict.getAutovalues())) {
            DictItem di = dao.findFirstByDictAndVal(dict, vo.getVal());
            if (di != null && !di.getId().equals(vo.getId()))
                throw new JDiyException(dict.getValName() + "[" + vo.getVal() + "]与现有条目重复．");
        }
        DictItem po = dao.findById(vo.getId()).orElseGet(() -> {
            DictItem po1 = new DictItem();
            po1.setRemovable(true);
            po1.setEditable(true);
            po1.setHidden(false);
            return po1;
        });
        po.setTxt(vo.getTxt());
        boolean isAdd = po.getVal() == null;
        po.setVal(vo.getVal());
        if (dict.getType() == 3) {//k/v/color
            po.setColor(vo.getColor());
        }
        po.setDict(vo.getDict());
        po.setSortIndex(vo.getSortIndex());
        po = dao.save(po);
        //保证仅在添加时设置其值，修改时不应该再更新值已防对现有业务数据产生影响.
        if (isAdd && dict.getType() != 1 && Boolean.TRUE.equals(dict.getAutovalues())) po.setVal("" + po.getId());
        return dao.save(po);
    }


    @Override
    public void deleteById(Long aLong) {
        findById(aLong).ifPresent(x -> dao.delete(x));//for refresh cache
    }

    @Resource
    DictDao dictDao;
}
